<template>
	<view class="location-picker-page">
		<!-- 1. 自定义导航栏 -->
		<u-navbar title="添加位置" @leftClick="goBack" :safeAreaInsetTop="true" :autoBack="false" bgColor="#ffffff" placeholder>
		</u-navbar>

		<!-- 2. "足迹地图" 横幅 -->
		<view class="banner" @click="handleBannerClick">
			<view class="banner-content">
				<u-icon name="map-fill" color="#F7C146" size="20"></u-icon>
				<view class="banner-text">
					<text class="main-text">足迹地图</text>
					<text class="sub-text">带定位发视频 记录足迹领20元券</text>
				</view>
			</view>
			<u-icon name="arrow-right" color="#B8B8B8" size="14"></u-icon>
		</view>

		<!-- 3. 城市切换Tabs -->
		<u-tabs :list="cityTabs" :current="currentTabIndex" @change="onTabChange" lineColor="#000000"
			:activeStyle="{ color: '#000', fontWeight: 'bold' }" :inactiveStyle="{ color: '#666' }"></u-tabs>

		<!-- 4. 搜索框 -->
		<view class="search-container">
			<u-search placeholder="搜索位置" v-model="keyword" :showAction="false" @search="handleSearch"
				@clear="handleSearchClear"></u-search>
		</view>

		<!-- 5. 位置列表 -->
		<scroll-view scroll-y class="location-list-scroll" @scrolltolower="loadMore">
			<view class="location-list">
				<view class="location-item" v-for="(item, index) in locationList" :key="item.uid || index"
					@click="selectLocation(item)">
					<view class="item-info">
						<text class="item-name">{{ item.name }}</text>
						<text class="item-address">{{ item.address || ' ' }}</text>
					</view>
					<text v-if="item.distance" class="item-distance">{{ formatDistance(item.distance) }}</text>
				</view>
			</view>

			<!-- 加载和空状态提示 -->
			<u-loadmore :status="loadStatus" />
			<u-empty v-if="locationList.length === 0 && loadStatus === 'nomore'" mode="search" text="未找到相关位置" marginTop="100rpx"></u-empty>
		</scroll-view>
	</view>
</template>

<script>
	import { searchPlaces, getNearbyPlaces } from '@/utils/mapService.js';
	import { getDistance } from '@/utils/distance.js'; // 假设你将距离计算函数放在一个单独的文件中

	export default {
		data() {
			return {
				keyword: '',
				cityTabs: [{ name: '淮安' }, { name: '宿迁' }, { name: '常州' }],
				currentTabIndex: 0,
				locationList: [],
				currentGpsLocation: null,
				eventChannel: null,
				
				// 分页和加载状态
				pageNum: 0,
				isLoading: false,
				loadStatus: 'loadmore', // 'loadmore', 'loading', 'nomore'
				isSearching: false, // 标记当前是搜索模式还是周边模式
			};
		},
		onLoad() {
			this.eventChannel = this.getOpenerEventChannel();
			this.getCurrentLocationAndFetch();
		},
		methods: {
			goBack() { uni.navigateBack(); },
			
			getCurrentLocationAndFetch() {
				this.isLoading = true;
				this.loadStatus = 'loading';
				uni.getLocation({
					type: 'gcj02',
					success: (res) => {
						this.currentGpsLocation = {
							latitude: res.latitude,
							longitude: res.longitude
						};
						this.fetchNearbyPlaces(true); // true表示重置
					},
					fail: () => {
						uni.showToast({ title: '定位失败', icon: 'none' });
						this.addCityOptionToList([]);
						this.isLoading = false;
						this.loadStatus = 'nomore';
					}
				});
			},

			async fetchNearbyPlaces(isReset = false) {
				if (this.isLoading) return;
				if (isReset) {
					this.pageNum = 0;
					this.locationList = [];
					this.loadStatus = 'loadmore';
				}
				if (this.loadStatus === 'nomore') return;

				this.isLoading = true;
				this.loadStatus = 'loading';
				this.isSearching = false;

				try {
					const results = await getNearbyPlaces({
						latitude: this.currentGpsLocation.latitude,
						longitude: this.currentGpsLocation.longitude,
						pageNum: this.pageNum
					});
					
					this.addDistanceToResults(results);
					const newList = isReset ? [] : this.locationList;
					newList.push(...results);

					if (isReset) {
						this.addCityOptionToList(newList);
					} else {
						this.locationList = newList;
					}
					
					if (results.length < 20) {
						this.loadStatus = 'nomore';
					} else {
						this.pageNum++;
						this.loadStatus = 'loadmore';
					}
				} catch (error) {
					this.loadStatus = 'loadmore';
					uni.showToast({ title: error, icon: 'none' });
				} finally {
					this.isLoading = false;
				}
			},

			async handleSearch(isReset = false) {
				const city = this.cityTabs[this.currentTabIndex].name;
				const keyword = this.keyword.trim();
				if (!keyword) {
					this.handleSearchClear();
					return;
				}

				if (this.isLoading) return;
				if (isReset) {
					this.pageNum = 0;
					this.locationList = [];
					this.loadStatus = 'loadmore';
				}
				if (this.loadStatus === 'nomore' && !isReset) return;

				this.isLoading = true;
				this.loadStatus = 'loading';
				this.isSearching = true;
				
				try {
					const results = await searchPlaces({ keyword, city, pageNum: this.pageNum });
					this.addDistanceToResults(results);
					this.locationList.push(...results);
					
					if (results.length < 20) {
						this.loadStatus = 'nomore';
					} else {
						this.pageNum++;
						this.loadStatus = 'loadmore';
					}
				} catch (error) {
					this.loadStatus = 'loadmore';
					uni.showToast({ title: error, icon: 'none' });
				} finally {
					this.isLoading = false;
				}
			},
			
			handleSearchClear() {
				this.keyword = '';
				this.fetchNearbyPlaces(true);
			},
			
			loadMore() {
				if(this.isSearching) {
					this.handleSearch(false);
				} else {
					this.fetchNearbyPlaces(false);
				}
			},

			onTabChange(tab) {
				this.currentTabIndex = tab.index;
				this.handleSearch(true); // 切换城市后立即按关键词搜索
			},
			
			selectLocation(location) {
				if (this.eventChannel) {
					this.eventChannel.emit('onLocationSelect', location);
					uni.navigateBack();
				}
			},

			formatDistance(meters) {
				if(typeof meters !== 'number') return '';
				if (meters < 1000) return `${meters.toFixed(0)}m`;
				return `${(meters / 1000).toFixed(2)}km`;
			},

			addDistanceToResults(results) {
				if (!this.currentGpsLocation) return;
				results.forEach(item => {
					if (item.latitude && item.longitude) {
						item.distance = getDistance(
							this.currentGpsLocation.latitude, this.currentGpsLocation.longitude,
							item.latitude, item.longitude
						);
					}
				});
			},

			addCityOptionToList(list) {
				const city = this.cityTabs[this.currentTabIndex].name;
				list.unshift({
					name: `${city}市`,
					address: `中国江苏省${city}市`,
					uid: `city_${city}` // 给一个唯一的ID
				});
				this.locationList = list;
			},
			
			handleBannerClick(){ uni.showToast({title:'活动暂未开启',icon:'none'}); }
		}
	}
</script>

<style lang="scss" scoped>
/* 样式与上一个回答中的 `location-picker.vue` 样式一致，此处不再重复，请直接复制 */
.location-picker-page {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #ffffff;
}
.banner {
	display: flex; align-items: center; justify-content: space-between;
	padding: 16rpx 30rpx; background-color: #EBF8F7;
	border-radius: 16rpx; margin: 20rpx 30rpx;
	.banner-content { display: flex; align-items: center; }
	.banner-text {
		display: flex; flex-direction: column; margin-left: 16rpx;
		.main-text { font-size: 28rpx; font-weight: bold; color: #000; }
		.sub-text { font-size: 24rpx; color: #666; }
	}
}
.search-container { padding: 20rpx 30rpx; }
.location-list-scroll { flex: 1; overflow-y: auto; }
.location-list {
	.location-item {
		display: flex; align-items: center; justify-content: space-between;
		padding: 24rpx 30rpx; border-bottom: 1rpx solid #f0f0f0;
		.item-info {
			display: flex; flex-direction: column;
			.item-name { font-size: 30rpx; color: #303133; margin-bottom: 8rpx; }
			.item-address { font-size: 24rpx; color: #909399; }
		}
		.item-distance { font-size: 24rpx; color: #909399; }
	}
}
</style>